package core.util;

import java.io.Serializable;

public class MyCookieValue implements Serializable
{
    /**
     * 
     */
    private static final long serialVersionUID = 4716528565508690519L;

    private String sessionId;

    private int version;

    private long expireTime;
    
    private Locations locations;

    public void setLocations( Locations locations ) {
        this.locations = locations;
    }

    private MyCookieValue(){
    }
    
    public static MyCookieValue buildFromString(String value){
    	MyCookieValue result = new MyCookieValue();
    	
    	if(value == null) return null;
    	
    	String split[] = value.split("/");
    	if(split.length < 3) return null;
    	
    	result.sessionId = split[0];
    	try{
    		result.version = Integer.parseInt(split[1]);
    		result.expireTime = Long.parseLong(split[2]);
    	}catch(NumberFormatException e){
    		return null;
    	}
        if( split.length == 3 ) {
            result.locations = new Locations();
        } else {
            result.locations = new Locations( split[3] );
        }
    	return result;    	
    }    
    
    public MyCookieValue( String sessionId, int version, long expireTime, String location) {
        this.sessionId = sessionId;
        this.version = version;
        this.expireTime = expireTime;
        this.locations = new Locations( location );
    }

    public String getSessionId() {
        return sessionId;
    }

    public int getVersion() {
        return version;
    }

    public void increaseVersion() {
        version++;
    }

    public Locations getLocation() {
        return locations;
    }

    public long getExpireTime(){
    	return expireTime;
    }
    
    public long refreshExpireTime(){
    	expireTime = System.currentTimeMillis() + StoredData.TIME_OUT_MILLIS;
    	return expireTime;
    }
    
    @Override
    public String toString() {
        return sessionId + "/" + version + "/" + expireTime + "/"  + locations;
    }

    @Override
    public boolean equals( Object obj ) {
        if( this == obj )
            return true;
        if( obj == null )
            return false;
        if( getClass() != obj.getClass() )
            return false;
        MyCookieValue other = (MyCookieValue) obj;
        if( locations == null ) {
            if( other.locations != null )
                return false;
        } else if( !locations.equals( other.locations ) )
            return false;
        if( sessionId == null ) {
            if( other.sessionId != null )
                return false;
        } else if( !sessionId.equals( other.sessionId ) )
            return false;
        if( version != other.version ) {
            return false;
        }
        if(expireTime != other.expireTime){
        	return false;
        }
        return true;
    }

}
